﻿
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace LS.Nc6.Web.Entry.Controllers
{
    [Authorize]
    public class UploadController : Controller
    {
        private readonly ISysFileService _fileService;
        public UploadController(ISysFileService fileService)
        {
            _fileService = fileService;
        }
        [HttpPost]
        public async Task<ResponseDataResult> UploadFile(IFormFile file, string category)
        {
            ResponseDataResult rr = new ResponseDataResult();
            rr.code = 0;
            rr.message = "";
            //string category = RequestHelper.FilterParam(Request.Form["category"]);

            var ISysFileService = new SysFileService();
            if (null != file)
            {

                string url = string.Empty;
                try
                {
                    var uploadPath = "/Upload/" + category + "/";
                    //for (int i = 0; i < files.Count; i++)
                    //{
                    bool isFlag = IsAllowExtension(file);
                    if (isFlag) //验证大小
                    {
                        if (file.Length > 52428800)
                        {
                            rr.code = 1;
                            rr.message = "超过上传大小限制50M";
                            return rr;
                        }
                    }
                    else
                    {
                        rr.code = 1;
                        rr.message = "不允许上传文件类型";
                        return rr;
                    }
                    var filePath = DateTime.Now.ToString("yyyy-MM");
                    string filename = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);
                    string path = CoreHttpContext.MapPath(uploadPath.TrimStart('/') + filePath);

                 

                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    string filepath = path + "/" + filename;
                    using (var stream = new FileStream(filepath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);

                    }
                  
                    url = uploadPath + filePath + "/" + filename;
                    // }
                    var sufix = Path.GetExtension(file.FileName);
                    var entityId = await _fileService.InsertAsync(new SysFileEntity
                    {
                        Bizeid = "0",
                        Bizetype = category,
                        //Createby = UserInfo.UserId.ToString(),
                        CreateDate = DateTime.Now,
                        Fnewname = filename,
                        Foname = file.FileName,
                        IsDeleted = 0,
                        Fpath = url,
                        Fsize = file.Length.ToString(),
                        Ftype = sufix
                    });


                    rr.code = 0;
                    rr.message = "上传成功！";
                    rr.data = new { code = 0, filename = file.FileName, url = uploadPath + filePath + "/" + filename, id = entityId };
                    return rr;
                }
                catch (Exception ex)
                {
                    Log.Error($"UploadFile:ex={ex.Message.ToString()}");
                    rr.code = 1;
                    rr.message = ex.Message;
                }
            }
            return rr;
        }

        [HttpPost]
        public async Task<ResponseDataResult> UploadTinymceFile(IFormFile file, string category)
        {
            ResponseDataResult rr = new ResponseDataResult();
            rr.code = 0;
            rr.message = "";
            //string category = RequestHelper.FilterParam(Request.Params["category"]);
           

            var ISysFileService = new SysFileService();
            if (null != file)
            {
                // var urls = new string[files.Count];
                string url = string.Empty;
                try
                {
                    var uploadPath = "/Upload/" + category + "/";
                    //for (int i = 0; i < files.Count; i++)
                    //{
                   
                    bool isFlag = IsAllowExtension(file);
                    if (isFlag) //验证大小
                    {
                        if (file.Length > 52428800)
                        {
                            rr.code = 1;
                            rr.message = "超过上传大小限制50M";
                            return rr;
                        }
                    }
                    else
                    {
                        rr.code = 1;
                        rr.message = "不允许上传文件类型";
                        return rr;
                    }
                    var filePath = DateTime.Now.ToString("yyyy-MM");
                    string filename = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);
                    string path = CoreHttpContext.MapPath(uploadPath + filePath);
                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    string filepath = path + "/" + filename;
                    using (var stream = new FileStream(filepath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);

                    }
                    url = uploadPath + filePath + "/" + filename;
                    // }
                    var sufix = Path.GetExtension(file.FileName);
                    var entityId = await _fileService.InsertAsync(new SysFileEntity
                    {
                        Bizeid = "0",
                        Bizetype = category,
                        //Createby = UserInfo.UserId.ToString(),
                        CreateDate = DateTime.Now,
                        Fnewname = filename,
                        Foname = file.FileName,
                        IsDeleted = 0,
                        Fpath = url,
                        Fsize = file.Length.ToString(),
                        Ftype = sufix
                    });
                    rr.code = 0;
                    rr.message = "上传成功！";
                   
                    rr.data = "/Upload/" + category + "/" + filePath + "/" + filename;
                    return rr;
                }
                catch (Exception ex)
                {
                    Log.Error($"UploadTinymceFile:ex={ex.Message.ToString()}");
                    rr.code = 1;
                    rr.message = ex.Message;
                }
            }
            return rr;
        }

        #region 私有方法
        /// <summary>
        /// 验证后缀名
        /// </summary>
        /// <returns></returns>
        private bool IsAllowExtension(IFormFile filename)
        {
            if (filename != null)
            {
                string suffix = filename.FileName.Substring(filename.FileName.LastIndexOf("."));
                List<string> listextension = new List<string> {
            ".xls",".xlsx",".doc",".docx",".pdf",".jpg",".jpeg",".gif","",".bmp",".png",".mp4"
            };
                if (listextension.Contains(suffix.ToLower())) return true;
            }
            return false;
        }
        private static bool IsAllowedExtension(IFormFile file)
        {
            BinaryReader reader = new BinaryReader(file.OpenReadStream());

            Dictionary<string, string> diclist = new Dictionary<string, string> {

            {"208207","doc|xls|ppt|wps"},
            {"8075","docx|pptx|xlsx|zip"},
            {"108101","txt"},
            {"8297","rar"},
            {"7790","exe"},
            {"3780","pdf"},
            {"6033","htm|html"},
            {"255216","jpg"},
            {"7173","gif"},
            {"13780","png"},
            {"6677","bmp"},
            {"64101","bat"}
            };
            string fileclass = "";
            try
            {
                for (int i = 0; i < 2; i++)
                {
                    fileclass += reader.ReadByte().ToString();
                }
            }
            catch (Exception)
            {
                throw;
            }
            if (diclist.ContainsKey(fileclass))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

    }
}